import BankModal from '@/pages/base/bank/Modal'
import ExpenseModal from '@/pages/base/expense/Modal'
import ProductModal from '@/pages/base/product/Modal'
import WareModal from '@/pages/base/warehouse/Modal'
import {DashOutlined} from '@ant-design/icons'
import {Input} from 'antd'
import React, {useState} from 'react'
import css from './index.module.less'

export default function Inputs(props) {
  const {value, onChange, name, type, disabled, readonly} = props
  const ref = React.useRef()
  const [val, setVal] = useState(value)
  const [visible, setVisible] = useState(false)
  const [res, setRes] = useState()

  React.useEffect(() => {
    if (value !== val) {
      setVal(value)
      if (typeof value !== 'undefined') {
        setRes(value)
      }
    }
  }, [value])

  // 弹窗中确定
  function onModalOk(res) {
    setVisible(false)
    setVal(res[name])
    setRes(res[name])
    onChange(res)
  }

  // 弹窗中取消
  function onModalCancel() {
    setVisible(false)
  }

  // 渲染弹窗
  function renderModal() {
    let modal

    switch (type) {
      case 'warehouse':
        modal = <WareModal searchKey={name}
                           searchValue={val}
                           onOk={onModalOk}
                           onCancel={onModalCancel}/>
        break
      case 'product':
        modal = <ProductModal searchKey={name}
                              searchValue={val}
                              onOk={onModalOk}
                              onCancel={onModalCancel}/>
        break
      case 'bank':
        modal = <BankModal searchKey={name}
                           searchValue={val}
                           onOk={onModalOk}
                           onCancel={onModalCancel}/>
        break
      case 'expense':
        modal = <ExpenseModal searchKey={name}
                              searchValue={val}
                              onOk={onModalOk}
                              onCancel={onModalCancel}/>
        break
      default:
        break
    }

    return modal
  }

  // 输入框输入
  function handleChange(e) {
    setVal(e.target.value)
  }

  // 输入框回车
  function handlePressEnter(e) {
    console.log('E=', e)
    e.stopPropagation()
    setVisible(true)
  }

  // 输入框失去焦点
  function handleBlur() {
    setVal(res)
  }

  return <div className={css.ipt}>
    {
      readonly ? val : (
        <div style={{position: 'relative'}}>
          <Input
            ref={ref}
            disabled={disabled}
            variant="borderless"
            value={val}
            onBlur={handleBlur}
            onChange={handleChange}
            onPressEnter={handlePressEnter}
          />
          <DashOutlined className={css.iptDash} onClick={handlePressEnter}/>
          {visible ? renderModal() : null}
        </div>
      )
    }
  </div>
}